/**
 * @Description: 鬼少浮窗播放器免费版 v1.5
 * @Author: 鬼少
 * @Author URL: http://tv1314.com
 */
if ((navigator.userAgent.match(/(iPhone|iPod|Ipad|Android|ios)/i))) {wenkmTips.show('不支持播放器.');$("#wenkmPlayer").css("display", "none")} else {
var audio=new Audio(),
	$player=$('#wenkmPlayer'),
	$btns=$('.status',$player),
	$songName=$('.song',$player),
	$cover=$('.cover',$player),
	$songTime = $(".time", $player),
	$songFrom=$('.player .artist',$player),
	$songFrom1=$('.player .artist1',$player),
	roundcolor='#6c6971',
	lightcolor='#81c300',
	resourcePath='http://fm.tv1314.com/',
	playListFile=resourcePath+'api/music.php?vid=',
	lrcFile=resourcePath+'api/lrc.php?wd=',
	kscFile=resourcePath+'api/krc.php?wd=',
	volume=.55,
	albumId=0,
	songTotal=0,
	showLrc=true,
	musicfirsttip = !1,
	retries = 4,
	retry = 1,
	random=false;

function wenkmCicle(){
$songTime.text(formatSecond(audio.currentTime) + " / " + formatSecond(audio.duration));
	if(audio.currentTime<audio.duration/2){
		$btns.css('background-image','linear-gradient(90deg, '+ roundcolor +' 50%, transparent 50%, transparent), linear-gradient('+ (90+(270-90)/(audio.duration/2)*audio.currentTime) +'deg, '+ lightcolor +' 50%, '+ roundcolor +' 50%, '+ roundcolor +')');
	}else{
		$btns.css('background-image','linear-gradient('+ (90+(270-90)/(audio.duration/2)*audio.currentTime) +'deg, '+ lightcolor +' 50%, transparent 50%, transparent), linear-gradient(270deg, '+ lightcolor +' 50%, '+ roundcolor +' 50%, '+ roundcolor +')')
	}
}
	function formatSecond(t) {
		return ("00" + Math.floor(t / 60)).substr(-2) + ":" + ("00" + Math.floor(t % 60)).substr(-2)
	}
var cicleTime=null;
var wenkmMedia={
	play:function(){
		$player.addClass('playing');
		cicleTime=setInterval(wenkmCicle,800);
		wenkmTips.show('开始播放：'+wenkmList[albumId].song_name[songId]);
		if(hasLrc){
			lrcTime=setInterval(wenkmLrc.lrc.play,500);
			$('#wenkmLrc').addClass('show');
		};
		if(hasKsc){
			kscTime=setInterval(wenkmLrc.ksc.play,95);
			$('#wenkmKsc').addClass('show');
		};
	},
	pause:function(){
		clearInterval(cicleTime);
		$player.removeClass('playing');
		wenkmTips.show('暂停播放');
		if(hasLrc){
			clearTimeout(lrcTime);
			$('#wenkmLrc').removeClass('show');
		};
		if(hasKsc){
			clearTimeout(kscTime);
			$('#wenkmKsc').removeClass('show');
		};
	},
	error:function(){
				setTimeout(function(){
					if(retry == retries){
						wenkmMedia.next();
						wenkmTips.show(wenkmList[albumId].song_name[songId]+' - 资源错误，播放下一曲');
						retry = 1;//重置重试次数
					}else{
						wenkmMedia.getInfos(wenkmMedia.getSongId(songId));
						wenkmTips.show('加载歌曲失败 - 重试第'+retry+'次');
						$(".myhk_pjax_loading_frame,.myhk_pjax_loading").hide()
						retry = retry+1;
					}
				},2000);
	},
	seeking:function(){
		clearInterval(cicleTime);
		$player.removeClass('playing');
		wenkmTips.show('加载中...');
	},
	volumechange:function(){
		var vol=parseInt(audio.volume*100);
		$('.volume-on',$player).width(vol+'%');
		wenkmTips.show('音量：'+ vol +'%');
	},
	getInfos:function(id){
		songId=id;
		$.ajax({
			url:playListFile + wenkmList[albumId].song_id[songId] + '&key=' + crc32(wenkmList[albumId].song_id[songId]),
			type:'GET',
			dataType:'script',
			cache:false,
			success:function(){
				infos = infos[0]
				audio.src=infos.location;
				//歌曲名称
				$songName.text(LimitStr(wenkmList[albumId].song_name[songId]));
				//歌手及专辑
				$songFrom.text(LimitStr(wenkmList[albumId].artist_name[songId]));
				$songFrom1.text(LimitStr(infos.album_name));
				$songFrom1.attr('title',infos.album_name);
				//封面图案
				$cover.addClass('changing');
				var coverImg=new Image();
				coverImg.src=infos.album_cover;
				coverImg.onload=function(){
					setTimeout(function(){
						$cover.html(coverImg);
					},500)
					setTimeout(function(){
						$cover.removeClass('changing');
					},800)
				};
				coverImg.error=function(){
					$cover.html('').removeClass('changing');
				};
				//列表高亮当前播放项
				$('.mklist li',$player).eq(songId).addClass('current').find('.artist').html('正在播放&nbsp;>&nbsp;').parent().siblings().removeClass('current');
				//设置音量
				audio.volume=volume;
				//开始播放
				audio.play();
				//获取LRC
				wenkmLrc.load();
				$(".myhk_pjax_loading_frame,.myhk_pjax_loading").css("display", "none");
			},
			error:function(a,b,c){
				wenkmMedia.pause();
				$(".myhk_pjax_loading_frame,.myhk_pjax_loading").css("display", "none");
			}
		})
	},
	getSongId:function(n){
		return n>=songTotal ? 0 : n<0 ? songTotal-1 : n;
	},
	next:function(){
		if(random){
			wenkmMedia.getInfos(parseInt(Math.random()*songTotal))
		}else{
			wenkmMedia.getInfos(wenkmMedia.getSongId(songId+1))
		}
	},
	prev:function(){
		if(random){
			wenkmMedia.getInfos(parseInt(Math.random()*songTotal))
		}else{
			wenkmMedia.getInfos(wenkmMedia.getSongId(songId-1))
		}
	}
};
var wenkmTipsTime=null;
var wenkmTips={
	show:function(cont){
		clearTimeout(wenkmTipsTime);
		$('#wenkmTips').text(cont).addClass('show');
		this.hide();
	},
	hide:function(){
		wenkmTipsTime=setTimeout(function(){
			$('#wenkmTips').removeClass('show');
			0 == musicfirsttip && (musicfirsttip = !0, wenkmTips.show("~键：播放/暂停，左右键：上/下歌曲！"))
		},3000)
	}
};
audio.addEventListener('play',wenkmMedia.play,false);
audio.addEventListener('pause',wenkmMedia.pause,false);
audio.addEventListener('ended',wenkmMedia.next,false);
audio.addEventListener('playing',wenkmMedia.playing,false);
audio.addEventListener('volumechange',wenkmMedia.volumechange,false);
audio.addEventListener('error',wenkmMedia.error,false);
audio.addEventListener('seeking',wenkmMedia.seeking,false);

//播放器开关
$('.switch-player',$player).click(function(){
	$player.toggleClass('show');
	$('#wenkmKsc,#wenkmLrc').toggleClass('showPlayer')
});

//播放交互
$('.pause',$player).click(function(){
	audio.pause()
});
$('.play',$player).click(function(){
	audio.play()
});
$('.prev',$player).click(function(){
	wenkmMedia.prev()
	$(".myhk_pjax_loading_frame,.myhk_pjax_loading").css("display", "block");
});
$('.next',$player).click(function(){
	wenkmMedia.next()
	$(".myhk_pjax_loading_frame,.myhk_pjax_loading").css("display", "block");
});
$('.random',$player).click(function(){
	$(this).addClass('current');
	$('.loop',$player).removeClass('current');
	random=true;
	wenkmTips.show('随机播放');
});
$('.loop',$player).click(function(){
	$(this).addClass('current');
	$('.random',$player).removeClass('current');
	random=false;
	wenkmTips.show('顺序播放');
});
//音量交互
var $progress=$('.progress',$player);
$progress.click(function(e){
	var progressWidth=$progress.width(),
		progressOffsetLeft=$progress.offset().left;
	volume=(e.clientX-progressOffsetLeft)/progressWidth;
	audio.volume=volume;
});
var isDown=false;
$('.drag',$progress).mousedown(function(){
	isDown=true;
	$('.volume-on',$progress).removeClass('ts5');
});
$(window).on({
	mousemove:function(e){
		if(isDown){
			var progressWidth=$progress.width(),
				progressOffsetLeft=$progress.offset().left,
				eClientX=e.clientX;
			if(eClientX>=progressOffsetLeft && eClientX<=progressOffsetLeft+progressWidth){
				$('.volume-on',$progress).width((eClientX-progressOffsetLeft)/progressWidth*100+'%');
				volume=(eClientX-progressOffsetLeft)/progressWidth;
				audio.volume=volume;
			}
		}
	},
	mouseup:function(){
		isDown=false;
		$('.volume-on',$progress).addClass('ts5');
	}
});
//播放列表交互
$('.switch-playlist').click(function(){
	$player.toggleClass('showList')
});
//歌词
var hasLrc=false,//是否有lrc歌词
	hasKsc=false,//是否有ksc歌词
	kscLineNow1=false,//是否执行到第1行
	kscLineNow2=false,//是否执行到第2行
	lrcTimeLine=[],
	lrcHeight=$('#wenkmLrc').height(),
	lrcTime=null,
	kscTime=null,
	letterTime1=null,
	letterTime2=null,
	tempNum1=0,
	tempNum2=0;
var wenkmLrc={
	load:function(){
		wenkmLrc.lrc.hide();
		wenkmLrc.ksc.hide();
		$('#wenkmLrc,#wenkmKsc').html('');
		hasLrc=false;
		hasKsc=false;
		$.ajax({
			url:lrcFile + encodeURI(wenkmList[albumId].song_name[songId] + ' - ' + wenkmList[albumId].artist_name[songId]) + '&song_id=' + wenkmList[albumId].song_id[songId],
			type:'GET',
			dataType:'script',
			cache:false,
			success:function(){
				setTimeout(function(){
					wenkmLrc.lrc.format(cont);
				},500);
			},
			error:function(){
				setTimeout(function(){
					$('#wenkmLrc,#wenkmKsc').html('');
				},500);
			}
		})
/**模块不正常暂时放弃
		//载入KSC歌词（分开的目的是有时候会同步显示）
		if(wenkmList[albumId].song_lrc[songId].indexOf('krc')>=0){
			$.ajax({
				url:kscFile + encodeURI(wenkmList[albumId].song_id[songId]) + '.txt',
				cache:false,
				dataType:'text',
				success:function(cont){	
					setTimeout(function(){
						wenkmLrc.ksc.format(cont);
					},500);
				},
				error:function(){
					setTimeout(function(){
						$('#wenkmLrc,#wenkmKsc').html('');
					},500);
				}
			})
		};
		//载入LRC歌词
		if(wenkmList[albumId].song_lrc[songId].indexOf('lrc')>=0){
			$.ajax({
				url:lrcFile + encodeURI(wenkmList[albumId].song_name[songId] + ' - ' + wenkmList[albumId].artist_name[songId]) + '&song_id=' + wenkmList[albumId].song_id[songId],
				cache:false,
				dataType:'text',
				success:function(cont){	
					setTimeout(function(){
						wenkmLrc.lrc.format(cont);
					},500);
				},
				error:function(){
					setTimeout(function(){
						$('#wenkmLrc,#wenkmKsc').html('');
					},500);
				}
			})
		}
*/
	},
	lrc:{
		format:function(cont){
			hasLrc=true;
			function formatTime(t){
				var sp=t.split(':'),
					min=+sp[0],
					sec=+sp[1].split('.')[0],
					ksec=+sp[1].split('.')[1];
				return min*60+sec+Math.round(ksec/1000);
			};
			var lrcCont=cont.replace(/\[[A-Za-z]+:(.*?)]/g,'').split(/[\]\[]/g),
				lrcLine='';
			lrcTimeLine=[];
			for(var i=1; i<lrcCont.length; i+=2){
				var timer=formatTime(lrcCont[i]);
				lrcTimeLine.push(timer);
				lrcLine+='<li class="wenkmLrc'+ timer +'">'+ lrcCont[i+1] +'</li>'
			}
			$('#wenkmLrc').html('<ul>'+ lrcLine +'</ul>');
			setTimeout(function(){
				$('#wenkmLrc').addClass('show');
			},500);
			lrcTime=setInterval(wenkmLrc.lrc.play,500)
		},
		play:function(){
			var timeNow=Math.round(audio.currentTime);
			if($.inArray(timeNow, lrcTimeLine)>0){
				var $lineNow=$('.wenkmLrc'+timeNow);
				if(!$lineNow.hasClass('current')){
					$lineNow.addClass('current').siblings().removeClass('current');
					$('#wenkmLrc').animate({scrollTop:lrcHeight*$lineNow.index()})
				}
			}
		},
		hide:function(){
			clearInterval(lrcTime);
			$('#wenkmLrc').removeClass('show');
		}
	},
	ksc:{
		format:function(cont){
			hasKsc=true;
			var kscStartTimeLine=[],
				kscEndTimeLine=[],
				kscCont=[],
				kscTimePer=[],
				kscMain='',
				lineNow=0,
				sex='b';
			cont.replace(/\'(\d*):(\d*).(\d*)\',\s\'(\d*):(\d*).(\d*)\',\s\'(.*)\',\s\'(.*)\'/g,function(){
				var startMin=arguments[1] | 0,
					startSec=arguments[2] | 0,
					startKsec=arguments[3] | 0,
					endMin=arguments[4] | 0,
					endSec=arguments[5] | 0,
					endKsec=arguments[6] | 0;
				kscStartTimeLine.push(startMin*600+startSec*10+Math.round(startKsec/100));
				kscEndTimeLine.push(endMin*600+endSec*10+Math.round(endKsec/100));
				kscCont.push(arguments[7]);
				kscTimePer.push(arguments[8]);
			});
			for(var i=0; i<kscStartTimeLine.length; i++){
				var kscText='',
					kscTextPerTime=kscTimePer[i].split(',');
				if(kscCont[i].indexOf('(男:)')>=0){
					sex='b';
					kscCont[i]=kscCont[i].replace('(男:)','');
				};
				if(kscCont[i].indexOf('(女:)')>=0){
					sex='g';
					kscCont[i]=kscCont[i].replace('(女:)','');
				};
				if(kscCont[i].indexOf('(合:)')>=0){
					sex='t';
					kscCont[i]=kscCont[i].replace('(合:)','');
				};
				for(var j=0; j<kscCont[i].length; j++){
					if(kscCont[i][j]=='，'){
						kscText+='<span class="blank"><em dir="'+ kscTextPerTime[j] +'"></em></span>'
					}else{
						kscText+='<span><em dir="'+ kscTextPerTime[j] +'">'+ kscCont[i][j] +'</em></span>'
					}
				}
				kscMain+='<div id="wenkmKsc'+ kscEndTimeLine[i] +'" class="wenkmKsc'+ kscStartTimeLine[i] +' line line'+ (i%2==0 ? 1 : 2) +' '+ sex +'"><div class="bg">'+ kscText +'</div><div class="lighter">'+ kscText +'</div></div>'
			}
			$('#wenkmKsc').html(kscMain);
			setTimeout(function(){
				$('#wenkmKsc').addClass('show');
			},500);
			kscTime=setInterval(wenkmLrc.ksc.play,80);
		},
		play:function(){
			var timeNow=Math.round(audio.currentTime*10);
			//提前1s显示某行歌词
			if($('.wenkmKsc'+(timeNow+10)).length && !$('.wenkmKsc'+(timeNow+10)).hasClass('current')){
				var $kscId=$('.wenkmKsc'+(timeNow+10));
				$kscId.addClass('current');
				//间隔时间短的话，还未到隐藏时间，防止歌词交叉重叠
				$kscId.hasClass('line1') ? $kscId.siblings('.line1').removeClass('current') : $kscId.siblings('.line2').removeClass('current');
				//1s后执行每个字幕
				setTimeout(function(){
					if($kscId.hasClass('line1')){
						wenkmLrc.ksc.showLetters.line1($kscId);
						kscLineNow1=true;
					}else{
						wenkmLrc.ksc.showLetters.line2($kscId);
						kscLineNow2=true;
					}
				}, 1000);
			};
			//3s后自动隐藏某行歌词
			if($('#wenkmKsc'+(timeNow-30)).length){
				$('#wenkmKsc'+(timeNow-30)).removeClass('current')
			}
		},
		//显示每个字幕
		showLetters:{
			//第一行（分开的目的是为了避免多行同时显示出错）
			line1:function(id){
				var $span=$('.lighter span',id),
					$spanNow=$span.eq(tempNum1++),
					$em=$('em',$spanNow),
					spanT=+$em.attr('dir');
				$em.animate({width:'100%'}, spanT);
				if(tempNum1<$span.length){
					letterTime1=setTimeout(function(){
						wenkmLrc.ksc.showLetters.line1(id)
					}, spanT);
				}else{
					tempNum1=0;
					kscLineNow1=false;
				}
			},
			//第二行
			line2:function(id){
				var $span=$('.lighter span',id),
					$spanNow=$span.eq(tempNum2++),
					$em=$('em',$spanNow),
					spanT=+$em.attr('dir');
				$em.animate({width:'100%'}, spanT);
				if(tempNum2<$span.length){
					letterTime2=setTimeout(function(){
						wenkmLrc.ksc.showLetters.line2(id)
					}, spanT);
				}else{
					tempNum2=0;
					kscLineNow2=false;
				}
			}
		},
		hide:function(){
			clearInterval(kscTime);
			$('#wenkmKsc').removeClass('show');
		}
	}
}};
//限制字符个数，并在末尾加上自定义字符
function LimitStr(str, num, t) {
        num = num || 9;
        //限制字符数默认为11个，注意，两个英文字符，算一个！！！
        t = t || '...';
        //默认在末尾加上省略号
        var re = '';
        var leg = str.length;
        var h = 0;
        for (var i = 0; h < num * 2 && i < leg; i++) {
            h += str.charCodeAt(i) > 128 ? 2: 1;
            re += str.charAt(i);
        }
        if (i < leg) re += t;
        return re;
}
//crc32
function crc32(e) {
	var t, r, n, a = new Array(256);
	for (t = 0; 256 > t; t++) {
		for (n = t, r = 0; 8 > r; r++) n = 1 & n ? n >> 1 & 2147483647 ^ 3988292384 : n >> 1 & 2147483647;
		a[t] = n
	}
	for ("string" != typeof e && (e = "" + e), n = 4294967295, t = 0; t < e.length; t++) n = n >> 8 & 16777215 ^ a[255 & n ^ e.charCodeAt(t)];
	return n ^= 4294967295, (n >> 3).toString(16)
}
//载入歌曲列表
function get_user_id(user_id){
$(".myhk_pjax_loading_frame,.myhk_pjax_loading").css("display", "block");
$.ajax({
	url:resourcePath + 'user/love.php?type=json&tuid=' + user_id,
	type:'GET',
	dataType:'script',
	success:function(){
		get_data(ids);
	},
	error:function(XMLHttpRequest, textStatus, errorThrown){
		wenkmTips.show('歌曲列表获取失败.')
	}
});
}
//云歌曲
function get_data(ids){
$(".myhk_pjax_loading_frame,.myhk_pjax_loading").css("display", "block");
$.ajax({
	url:resourcePath + 'api/music.php?ids=' + encodeURIComponent(ids) + '&code=' + crc32(ids),
	type:'GET',
	dataType:'script',
	success:function(){
		$(".myhk_pjax_loading_frame,.myhk_pjax_loading").css("display", "none");
		wenkmTips.show('歌曲列表已载入成功.')
		var listdata = '<div style="margin-left: 20px;"><a onclick="get_data(-1);">换歌</a></div>';
		$('.mkheader',$player).html(listdata);
		songTotal=wenkmList[albumId].song_id.length;
		var li='';
		for(var i=0; i<songTotal; i++){
			li+='<li><span class="index">'+ (i+1) +'</span>'+'<span class="artist"></span>' + LimitStr(wenkmList[albumId].song_name[i] + '&nbsp;-&nbsp;' + wenkmList[albumId].artist_name[i],30) +'</li>';
		};
		$('.mklist',$player).html('<ul>'+ li +'</ul>').mCustomScrollbar();
		var songId=Math.floor(Math.random()*total);
		//如果有视频等播放就不播放音乐
		try{
			if($("#playerifarme").length){
				audio.pause();
			}else{
				wenkmMedia.getInfos(songId);
			}
		}catch(E){}
		$('.mklist li',$player).click(function(){
			$(".myhk_pjax_loading_frame,.myhk_pjax_loading").css("display", "block")
			$(this).hasClass('current') ? $(".myhk_pjax_loading_frame,.myhk_pjax_loading").css("display", "none") : wenkmMedia.getInfos($(this).index())
		});
	},
	error:function(XMLHttpRequest, textStatus, errorThrown){
		wenkmTips.show('歌曲列表获取失败.')
	}
})
}
//键盘事件
$(document).ready(function() {
	$(window).keydown(function(a) {
		a = a.keyCode;
		192 == a ? audio.paused ? (audio.play(), $(".mklist li", $player).eq(songId).addClass("current").find(".artist").html("正在播放&nbsp;>&nbsp;").parent().siblings().removeClass("current")) : (audio.pause(), $(".mklist li", $player).eq(songId).addClass("current").find(".artist").html("暂停播放&nbsp;>&nbsp;").parent().siblings().removeClass("current")) : 37 == a ? (wenkmMedia.prev(), $(".myhk_pjax_loading_frame,.myhk_pjax_loading").css("display", "block")) : 39 == a && (wenkmMedia.next(), $(".myhk_pjax_loading_frame,.myhk_pjax_loading").css("display", "block"))
	})
});